import { ajax, Login } from '../utils/ajax.js'
import { pwdTest } from '../utils/register.js'
import '../lib/jquery.js'

(async () => {
    //先看看登陆没
    let { status, user, token } = await Login();
    if (status == 0) {
        alert('请登录！')
        location.href = './login.html';
    }

    //表单的提交
    $('form').on('submit', async e => {
        //拦截一下你懂的
        e.preventDefault();
        //获取那个原始密码，新密码和确认新密码咯
        let oldPassword = $('.oldpassword').val().trim();
        let newPassword = $('.newpassword').val().trim();
        let rNewPassword = $('.rnewpassword').val().trim();

        //有一个为空的你就重写吧你
        if (oldPassword == '' || newPassword == '' || rNewPassword == '') return alert('每个都得填！');

        //否则判断新密码格式对不对
        if (!pwdTest(newPassword)) return alert('新密码格式不对哟');
        //接下来判断两次密码是否一致
        if (newPassword != rNewPassword) return alert('两次密码不一样！')

        //老规矩了发给服务器真的修改一下
        //看文档找要传给的数据
        let data = { id: user.id, oldPassword, newPassword, rNewPassword };

        //请求服务器咯
        let { data: {code, message} } = await ajax.post('/users/rpwd', data, { headers: { authorization: token } })

        if (code == 0) return alert('修改失败！')

        //还得删了本地存储！
        localStorage.removeItem('token');
        localStorage.removeItem('uid');
        
        alert(message)
        //跳转登录界面
        location.href = './login.html'
    })
})();